package tr.edu.yildiz.ce.dap.appagent.command.prompt;

import java.io.File;
import java.util.List;
import java.util.StringTokenizer;


import tr.edu.yildiz.ce.dap.appagent.command.deployment.agent.LocalCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractAgentCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.exception.AgentDeploymentException;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.model.AppDefinition;
import tr.edu.yildiz.ce.dap.appagent.model.Component;
import tr.edu.yildiz.ce.dap.appagent.model.ComponentList;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;
import tr.edu.yildiz.ce.dap.appagent.service.DapXmlConverter;
import tr.edu.yildiz.ce.dap.appagent.util.DeploymentUtils;

public class LocalInstallCommand extends BasicPromptCommand {

	public LocalInstallCommand(AbstractProcess process) {
		super(process);
	}

	@Override
	protected AbstractAgentCommand prepareAgentCommand(AbstractProcess process,
			String commandStr) throws BasicAgentException {
		StringTokenizer sTokenizer = new StringTokenizer(commandStr," ");
		String command = sTokenizer.nextToken();
		String filePath = null;
		while (sTokenizer.hasMoreElements()) {
			String pType = (String) sTokenizer.nextElement();
			if (pType.equals(CommandConstants.PARAMETER_TYPE.FILE)){
				filePath = sTokenizer.nextToken();
			}
		}
		
		ComponentList componentList;
		try {
			componentList = ((AppDefinition) DapXmlConverter.convertToObject(new File(filePath))).getComponentList();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BasicAgentException("Can't convert deployment file to object :" + e.getMessage() );
		}
		
		DapMessage dapMessage = new DapMessage();
		dapMessage.setComponentList(componentList);
		installComponents(componentList, process);
		return new LocalCommand(process);
	}
	
	private void installComponents(ComponentList componentList,AbstractProcess process) throws AgentDeploymentException{
		List<Component> cList = componentList.getComponent();
		for (Component component : cList) {
			String bundleLocation = DeploymentUtils.downloadBundle(component);
			DeploymentUtils.installBundle(component, bundleLocation,process.getProcessManager().getContext());
		}
		DapMessage dapMessage = new DapMessage();
		dapMessage.setResponse(CommandConstants.RESPONSE.OK);
	}

	@Override
	protected void processResponse(DapMessage response) {
		

	}

}
